package org.xtframe.service.impl;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jbpm.api.Execution;
import org.jbpm.api.task.Task;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.service.AjaxDataHandlerException;
import org.xtframe.util.ContextUtil;
import org.xtframe.util.JbpmUtil;
import org.xtframe.util.WorkflowUtil;

@Service
@Scope("prototype")
public class TaskPageDataHandler implements AjaxDataHandler {

	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			UserData userData = ContextUtil.getCurrentUserData();
			if(userData == null){
				map.put(STATUS, false);
				map.put(LOGIN, true);
				throw new AjaxDataHandlerException("未登陆获取任务页面", 1);
			}
			
			JSONObject objJson = JSONObject.fromObject(strData);
			if(!objJson.has("taskId")) throw new AjaxDataHandlerException("获取任务页面参数不正确");
			
			String taskId = objJson.optString("taskId");
			Task task = JbpmUtil.getInstance().getTaskByTaskId(taskId);
			String formValue = JbpmUtil.getInstance().getTaskByTaskId(taskId).getFormResourceName();
			Execution processInstance = JbpmUtil.getInstance().getExecutionService().findExecutionById(task.getExecutionId());
			
			Map<String, Object> taskPage = WorkflowUtil.getTaskPage(processInstance.getProcessDefinitionId(), formValue);
			if(taskPage == null){
				map.put(STATUS, false);
			} else {
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("processInstanceId", processInstance.getId());
				data.put("pageId", taskPage.get("pageid"));
				data.put("parameters", taskPage.get("parameters"));
				
				map.put(STATUS, true);
				map.put(OBJECT,  data);
			}
		} catch(AjaxDataHandlerException ex){
			logger.warn(ex.toString());
			if(ex.getFlag() == 0){
				map.clear();
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
